/**
 * This class makes the police station servant objects
 * as UDP servers to communicate worth eachother to send
 * receive record counts from one another.
 */
package com.comp6231.replica2.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author Farzana Alam
 * 
 */
public class OperationServer implements Runnable {

	// the port where the server will listen
	private int port;
	// the police station servant object
	private StationImpl stationServer;
	private static final String COUNTFLAG = "COUNT";
	private static final String TRANSFERFLAG = "TRANSFER";

	/**
	 * @param stationServer
	 * @param port
	 */
	public OperationServer(StationImpl stationServer, int port) {
		this.port = port;
		this.stationServer = stationServer;
	}

	@Override
	public void run() {
		System.out.println("UDP server for local "
				+ stationServer.getMyStationID()
				+ " station server is running at " + port);

		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket(port);
			byte[] buffer = new byte[1000];
			while (true) {
				DatagramPacket request = new DatagramPacket(buffer,
						buffer.length);
				socket.receive(request);

				String operation = new String(request.getData()).trim();
				String operationResult = "";
				if (operation.startsWith(COUNTFLAG)) {
					operationResult = stationServer.getLocalCount();
				}

				if (operation.startsWith(TRANSFERFLAG)) {
					operationResult = stationServer.recieveFromRemote(operation
							.substring(TRANSFERFLAG.length()));
				}

				DatagramPacket reply = new DatagramPacket(
						operationResult.getBytes(), operationResult.length(),
						request.getAddress(), request.getPort());
				socket.send(reply);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (socket != null)
				socket.close();
		}

	}

}
